﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using SharedLibraries;
using SharedLibraries.Constants;
using EntityObject;
using DataAccessObject;
using ThangNM_LIB.FUNC;
using ThangNM_LIB.DB;

namespace ThangNM.UserControl
{
    public partial class Media_ListUC : System.Web.UI.UserControl
    {

        #region "Properties & Event"
        public delegate void CustomerEventHandler(object sender, CustomerEventArgs args);
        public event CustomerEventHandler ViewDetail;
        public event CustomerEventHandler ViewMessage;
        public event EventHandler Insert;

        public SortDirection directionState
        {
            get { return (ViewState["directionState"] == null ? SortDirection.Descending : (SortDirection)ViewState["directionState"]); }
            set { ViewState["directionState"] = value; }
        }

        public Int16 FK_iCategoryID
        {
            get { return (ViewState["FK_iCategoryID"] == null ? Convert.ToInt16(0) : (Int16)ViewState["FK_iCategoryID"]); }
            set { ViewState["FK_iCategoryID"] = value; }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ToolBarUC1.ViewGroupButtonByFunction(ConstEx.funcButtonToolBar.LIST);
                ToolBarUC1.BindData_DropDownList(GetListConstants.Topic_iStatus_GLC(true));
                ToolBarUC1.SetDefaultValue(0);
                BindData_List(FK_iCategoryID, null);
            }
        }

        public void BindData_List(Int16 _FK_iCategoryID, String sSortColumn)
        {
            try
            {
                FK_iCategoryID = _FK_iCategoryID;
                List<MediaEO> lst = new List<MediaEO>();
                grvList.Visible = false;
                string keysearch = StringEx.Trim(SearchUI1.txtTextSearch.Text).ToUpper();
                DataTable dt = (new MediaDAO()).SelectBy_FK_iCategoryID_iState(FK_iCategoryID, Convert.ToInt16(ToolBarUC1.ddlStatus.SelectedValue));
                DataView dv = dt.DefaultView;
                if (!String.IsNullOrEmpty(sSortColumn))
                    dv.Sort = sSortColumn;
                else
                    dv.Sort = "[PK_iMediaID] DESC";
                dt = dv.ToTable();
                var result = (List<MediaEO>)ConvertEx.ConvertDataTableToListObject<MediaEO>(dt, lst.GetType());
                if (result != null)
                {
                    if (SearchUI1.ddlTypeSearch.SelectedValue.Equals("0"))
                    {
                        if (!String.IsNullOrEmpty(keysearch))
                        {
                            result = result.FindAll(x => StringEx.CompareEx(x.PK_iMediaID.ToString(),keysearch));
                        }
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(keysearch))
                        {
                            result = result.FindAll(x => StringEx.CompareEx(x.sName,keysearch));
                        }
                    }
                    if (result.Count() > 0)
                    {
                        grvList.Visible = true;
                        grvList.DataSource = result.ToList();
                        grvList.DataBind();
                        lblRowCount.Text = MessagesEx.Tong_So_Ban_Ghi + result.Count();
                        return;
                    }
                }
                grvList.DataSource = null;
                grvList.DataBind();
                lblRowCount.Text = MessagesEx.Khong_Thoa_Man_Dieu_Kien_Tim_Kiem;
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        public void ResetFormSearch()
        {
            SearchUI1.txtTextSearch.Text = "";
            SearchUI1.ddlTypeSearch.SelectedValue = "0";
        }

        #region "Event Handler"
        protected void Search_Click(object sender, EventArgs e)
        {
            BindData_List(FK_iCategoryID, null);
        }

        protected void EventButtonToolBar_Click(object sender, CustomerEventArgs e)
        {
            if ((new ShareDAO.UserDAO()).SelectBy_sPermission(Session["secret"], Convert.ToString(Request.Url.AbsolutePath), e.iType) == false)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.DANGER, MessagesEx.Khong_Co_Quyen_Truy_Cap, null));
                Commons.setAccessDenied(Page, null);
                return;
            }
            switch (e.iType)
            {
                case ConstEx.funcButtonToolBar.INSERT_LIST:
                    if (Insert != null)
                        Insert(this, EventArgs.Empty);
                    break;
                case ConstEx.funcButtonToolBar.INSERT_ITEM: break;
                case ConstEx.funcButtonToolBar.UPDATE_ITEM: break;
                case ConstEx.funcButtonToolBar.DELETE_LIST:
                    DeleteList();
                    break;
                case ConstEx.funcButtonToolBar.DELETE_ITEM: break;
                case ConstEx.funcButtonToolBar.REFRESH_LIST:
                    ResetFormSearch();
                    BindData_List(FK_iCategoryID, null);
                    break;
                case ConstEx.funcButtonToolBar.EXPORT_EXCEL:
                    if (grvList.PageCount > 0)
                    {
                        ExportEx.PDF_Export(grvList, "Media");
                    }
                    else
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, "Không thể xuất file vì không có bản ghi nào.", null));
                    }
                    break;
                case ConstEx.funcButtonToolBar.RESET_FORM: break;
            }
        }

        protected void EventSelectChange_Click(object sender, CustomerEventArgs e)
        {
            if (e != null)
            {
                BindData_List(FK_iCategoryID, null);
            }
        }
        #endregion

        #region "Event GridView"
        protected void grvList_RowCommand(object source, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "cmdView")
            {
                int rowIndex = Convert.ToInt32(e.CommandArgument) % grvList.PageSize;
                int PK_iMediaID = Convert.ToInt32(grvList.DataKeys[rowIndex].Values[0]);
                MediaEO _MediaEO = new MediaEO();
                _MediaEO = (new MediaDAO()).SelectItem(PK_iMediaID);
                if (ViewDetail != null)
                    ViewDetail(this, new CustomerEventArgs(1, "Oki", _MediaEO));
            }
        }

        protected void grvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvList.PageIndex = e.NewPageIndex;
            BindData_List(FK_iCategoryID, null);
        }

        protected void grvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (directionState == SortDirection.Ascending)
            {
                directionState = SortDirection.Descending;
                BindData_List(FK_iCategoryID, "[" + e.SortExpression + "]" + " DESC");
            }
            else
            {
                directionState = SortDirection.Ascending;
                BindData_List(FK_iCategoryID, "[" + e.SortExpression + "]" + " ASC");
            }
        }
        #endregion

        protected void DeleteList()
        {
            try
            {
                string strID = "";
                string strTitle = "";
                string sLinkByType = "";
                foreach (GridViewRow row in grvList.Rows)
                {
                    CheckBox chk = (CheckBox)row.FindControl("chkItem");
                    if (chk != null && chk.Checked)
                    {
                        strID += "," + grvList.DataKeys[row.RowIndex].Values["PK_iMediaID"];
                        sLinkByType = FileNameByFunction.Giai_Tri_ + GetTextConstants.Media_iType2sType_GTC(Convert.ToInt16(StringEx.getDefaultValue(grvList.DataKeys[row.RowIndex].Values["FK_iCategoryID"], 0)));
                        strTitle += "," + System.Configuration.ConfigurationManager.AppSettings["HOMEPAGE"] + sLinkByType + "/" + RewriteUrl.ConvertToUnSign(Convert.ToString(grvList.DataKeys[row.RowIndex].Values["sName"])) + "." + Convert.ToString(grvList.DataKeys[row.RowIndex].Values["PK_iMediaID"]) + FileNameByFunction.HTML;
                    }
                }
                if (String.IsNullOrEmpty(strID))
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.CHUA_CHON_DONG_NAO_DE_XOA, ConstEx.Table_Name_C.Media), null));
                    return;
                }
                //if (MediaDAO.Delete(strID.Substring(1), strTitle.Substring(1)))
                //{
                //    BindData_List(FK_iCategoryID,null);
                //    if (ViewMessage != null)
                //    {
                //        ViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Xoa_Thanh_Cong_Ma, ConstEx.Table_Name_C.Media, strID.Substring(1)), null));
                //    }
                //}
                //else
                //{
                //    if (ViewMessage != null)
                //    {
                //        ViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Xoa_That_Bai_Ma, ConstEx.Table_Name_C.Media, strID.Substring(1)), null));
                //    }
                //}
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        public void setViewMessage(object sender, CustomerEventArgs args)
        {
            if (ViewMessage != null)
                ViewMessage(sender, args);
        }




        //    #region "Properties & Event"
        //    public event EventHandler ViewDetail;
        //    public event EventHandler AddNew;

        //    private Int32 _PK_iMediaID;
        //    public Int32 PK_iMediaID
        //    {
        //        get { return this._PK_iMediaID; }
        //        set { _PK_iMediaID = value; }
        //    }

        //    public Int16 iType
        //    {
        //        get { return (Int16)ViewState["iType"]; }
        //        set { ViewState["iType"] = value; }
        //    }
        //    #endregion

        //    protected void Page_Load(object sender, EventArgs e)
        //    {
        //    }

        //    public void BindData(Int16 _iType)
        //    {
        //        iType = _iType;
        //        grvListBaiViet.Visible = false;
        //        string keysearch = txtTextSearch.Text;
        //        DataTable dtMedia = new DataTable();
        //        try
        //        {
        //            dtMedia = MediaDAO.SelectBy_iType(iType);
        //            var result =
        //            from Media in dtMedia.AsEnumerable()
        //            select new
        //            {
        //                PK_iMediaID = Media.Field<Int32>("PK_iMediaID"),
        //                sTitle = Media.Field<string>("sTitle"),
        //                sTag = Media.Field<string>("sTag"),
        //                iVisit = Media.Field<Int32>("iVisit"),
        //                iLike = Media.Field<Int32>("iLike"),
        //                tDateTimeCreate = Media.Field<DateTime>("tDateTimeCreate"),
        //                tDateTimeModify = Media.Field<DateTime>("tDateTimeModify"),
        //                iStatus = Media.Field<Int16>("iStatus")
        //            };
        //            if (Convert.ToInt16(ddlTypeSearch.SelectedValue) == 0)
        //            {
        //                if (keysearch != "")
        //                {
        //                    var search = (from item in result where item.PK_iMediaID.ToString().ToUpper().Contains(keysearch.ToString().ToUpper().Trim()) select item);
        //                    result = search;
        //                }
        //            }
        //            else
        //            {
        //                if (keysearch != "")
        //                {
        //                    var search = (from item in result where item.sTitle.ToString().ToUpper().Contains(keysearch.ToString().ToUpper().Trim()) select item);
        //                    result = search;
        //                }
        //            }
        //            if (result.Count() > 0)
        //            {
        //                grvListBaiViet.Visible = true;
        //                grvListBaiViet.DataSource = result.ToList();
        //                grvListBaiViet.DataBind();
        //                lblTongSoBanGhi.Text = MessagesEx.Tong_So_Ban_Ghi + result.Count();
        //            }
        //            else
        //            {
        //                lblTongSoBanGhi.Text = MessagesEx.Khong_Thoa_Man_Dieu_Kien_Tim_Kiem;
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            lblTongSoBanGhi.Text = MessagesEx.Loi + ex.Message;
        //        }
        //    }

        //    #region "Event GridView"
        //    protected void grvListBaiViet_RowCommand(object sender, GridViewCommandEventArgs e)
        //    {
        //        if (e.CommandName == "cmdView")
        //        {
        //            this.PK_iMediaID = Convert.ToInt32(e.CommandArgument);
        //            if (ViewDetail != null)
        //            {
        //                ViewDetail(this, EventArgs.Empty);
        //            }
        //        }
        //    }

        //    protected void grvListBaiViet_SelectedIndexChanged(object sender, EventArgs e)
        //    {
        //        foreach (GridViewRow row in grvListBaiViet.Rows)
        //        {
        //            if (row.RowIndex == grvListBaiViet.SelectedIndex)
        //            {
        //                row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
        //                row.ToolTip = string.Empty;
        //            }
        //            else
        //            {
        //                row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
        //                row.ToolTip = "Click to select this row.";
        //            }
        //        }
        //    }

        //    protected void grvListBaiViet_PageIndexChanging(object sender, GridViewPageEventArgs e)
        //    {
        //        grvListBaiViet.PageIndex = e.NewPageIndex;
        //        BindData(iType);
        //    }

        //    protected void grvListBaiViet_RowDataBound(object sender, GridViewRowEventArgs e)
        //    {
        //        if (e.Row.RowType == DataControlRowType.DataRow)
        //        {
        //            e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(grvListBaiViet, "Select$" + e.Row.RowIndex);
        //            e.Row.ToolTip = "Click to select this row.";
        //        }
        //    }

        //    protected void grvListBaiViet_Sorting(object sender, GridViewSortEventArgs e)
        //    {
        //        string sortingDirection = string.Empty;
        //        if (direction == SortDirection.Ascending)
        //        {
        //            direction = SortDirection.Descending;
        //            sortingDirection = "DESC";
        //        }
        //        else
        //        {
        //            direction = SortDirection.Ascending;
        //            sortingDirection = "ASC";
        //        }
        //        DataTable dtMedia = MediaDAO.SelectList();
        //        DataView sortedView = new DataView(dtMedia);
        //        sortedView.Sort = e.SortExpression + " " + sortingDirection;
        //        Session["objects"] = sortedView;
        //        grvListBaiViet.DataSource = sortedView;
        //        grvListBaiViet.DataBind();
        //    }

        //    public SortDirection direction
        //    {
        //        get
        //        {
        //            if (ViewState["directionState"] == null)
        //            {
        //                ViewState["directionState"] = SortDirection.Ascending;
        //            }
        //            return (SortDirection)ViewState["directionState"];
        //        }
        //        set
        //        { ViewState["directionState"] = value; }
        //    }
        //    #endregion

        //    #region "Event Button"
        //    protected void btnRefresh_Click(object sender, EventArgs e)
        //    {
        //        txtTextSearch.Text = "";
        //        BindData(iType);
        //    }

        //    protected void btnAddNew_Click(object sender, EventArgs e)
        //    {
        //        if (AddNew != null)
        //        {
        //            AddNew(this, EventArgs.Empty);
        //        }
        //    }

        //    protected void btnDeleteList_Click(object sender, EventArgs e)
        //    {

        //    }

        //    protected void btnExportExcel_Click(object sender, EventArgs e)
        //    {
        //    }
        //    #endregion

        //    protected void btnSearch_Click(object sender, EventArgs e)
        //    {
        //        BindData(iType);
        //    }
    }
}